package com.ijunfu.detail.threadpool;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 *
 * @Title  : 线程和线程池性能对比
 * @Author : ijunfu <ijunfu@163.com>
 * @Date   : 2023/11/24 13:00
 * @Version: 1.0
 * @Motto  : 世界很大 世界很小
 *
 */
@Slf4j
public class _01Main {

    public static void main(String[] args) throws InterruptedException {
        thread();

        threadpool();
    }

    public static void thread() {
        StopWatch stopWatch = new StopWatch();

        List<Integer> list = new ArrayList<>();
        stopWatch.start();
        IntStream.range(0,100000)
                .forEach((idx)->{
                    Thread t = new Thread(()->{
                        list.add(idx);
                    });

                    t.start();
                    try {
                        t.join();
                    } catch (InterruptedException e) {
                        t.interrupt();
                    }
                });
        stopWatch.stop();

        log.info("thread time={}ms", stopWatch.getLastTaskTimeMillis());
        log.info("thread list size={}", list.size());
    }

    public static void threadpool() throws InterruptedException {
        StopWatch stopWatch = new StopWatch();

        List<Integer> list = new ArrayList<>();
        stopWatch.start();
        ExecutorService pool = Executors.newSingleThreadExecutor();
        IntStream.range(0,100000)
                .forEach((idx)->{

                    pool.execute(()->{
                        list.add(idx);
                    });
                });
        pool.shutdown();
        pool.awaitTermination(1L, TimeUnit.DAYS);
        stopWatch.stop();

        log.info("threadpool time={}ms", stopWatch.getLastTaskTimeMillis());
        log.info("threadpool list size={}", list.size());
    }

}
